@using DaoHang.Services
@using DaoHang.Models
@namespace DaoHang.Components.Admin
@inject ISiteSettingsService SiteSettingsService
@inject IUserService UserService
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-gear me-2"></i>网站设置
        </h5>
    </div>
    <div class="card-body">
        @if (isLoadingSettings)
        {
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">加载中...</p>
            </div>
        }
        else
        {
            <div class="row">
                <!-- 基本设置 -->
                <div class="col-md-6 mb-4">
                    <div class="card border-info h-100">
                        <div class="card-header bg-info text-white">
                            <h6 class="mb-0"><i class="bi bi-info-square me-2"></i>基本设置</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">网站标题</label>
                                <input type="text" class="form-control" @bind="settings.SiteTitle" />
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">网站描述</label>
                                <textarea class="form-control" rows="3" @bind="settings.SiteDescription"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">关键词</label>
                                <input type="text" class="form-control" @bind="settings.SiteKeywords" 
                                       placeholder="多个关键词用逗号分隔" />
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">版权信息</label>
                                <input type="text" class="form-control" @bind="settings.CopyrightInfo" />
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">ICP备案号</label>
                                <input type="text" class="form-control" @bind="settings.IcpNumber" 
                                       placeholder="例如：京ICP备12345678号" />
                                <small class="text-muted">将在网站底部显示并链接到 <a href="https://beian.miit.gov.cn/" target="_blank">工信部备案管理系统</a></small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">公安备案号</label>
                                <input type="text" class="form-control" @bind="settings.PoliceNumber" 
                                       placeholder="例如：津公网安备12011202000841号" />
                                <small class="text-muted">
                                    将在网站底部显示备案图标和备案号，格式：图标+备案号，并链接到 
                                    <a href="https://beian.mps.gov.cn/#/query/webSearch" target="_blank">全国互联网安全管理服务平台</a>。
                                    如不填写则不显示公安备案信息。
                                </small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 外观设置 -->
                <div class="col-md-6 mb-4">
                    <div class="card border-success h-100">
                        <div class="card-header bg-success text-white">
                            <h6 class="mb-0"><i class="bi bi-palette me-2"></i>外观设置</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Logo URL</label>
                                <div class="input-group">
                                    <input type="url" class="form-control" @bind="settings.LogoUrl" />
                                    @if (!string.IsNullOrEmpty(settings.LogoUrl))
                                    {
                                        <span class="input-group-text">
                                            <img src="@settings.LogoUrl" alt="Logo预览" 
                                                 style="height: 24px; object-fit: contain;" 
                                                 onerror="this.style.display='none';" />
                                        </span>
                                    }
                                </div>
                                <small class="text-muted">网站Logo图片URL，建议尺寸为200x50像素</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Favicon URL</label>
                                <div class="input-group">
                                    <input type="url" class="form-control" @bind="settings.FaviconUrl" />
                                    @if (!string.IsNullOrEmpty(settings.FaviconUrl))
                                    {
                                        <span class="input-group-text">
                                            <img src="@settings.FaviconUrl" alt="Favicon预览" 
                                                 style="width: 16px; height: 16px; object-fit: contain;" 
                                                 onerror="this.style.display='none';" />
                                        </span>
                                    }
                                </div>
                                <small class="text-muted">网站图标URL，建议尺寸为32x32像素</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">主题色</label>
                                <div class="input-group">
                                    <input type="color" class="form-control form-control-color" 
                                           @bind="settings.ThemeColor" title="选择主题色" />
                                    <input type="text" class="form-control" @bind="settings.ThemeColor" 
                                           placeholder="#rrggbb" />
                                </div>
                                <small class="text-muted">网站主要配色，HEX格式，如：#3498db</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- AI推荐设置 -->
                <div class="col-md-6 mb-4">
                    <div class="card border-warning h-100">
                        <div class="card-header bg-warning text-dark">
                            <h6 class="mb-0"><i class="bi bi-robot me-2"></i>AI推荐设置</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">阿里云API Key</label>
                                <input type="password" class="form-control" @bind="settings.AliCloudApiKey" />
                                <small class="text-muted">用于AI推荐功能的阿里云API密钥</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">AI模型</label>
                                <input type="text" class="form-control" value="qwen3-235b-a22b" disabled />
                                <small class="text-muted">当前固定使用通义千问3.5模型</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 安全设置 -->
                <div class="col-md-6 mb-4">
                    <div class="card border-danger h-100">
                        <div class="card-header bg-danger text-white">
                            <h6 class="mb-0"><i class="bi bi-shield-lock me-2"></i>安全设置</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">管理员用户名</label>
                                <input type="text" class="form-control" @bind="adminUsername" />
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">管理员密码</label>
                                <input type="password" class="form-control" @bind="adminPassword" 
                                       placeholder="不修改请留空" />
                                <small class="text-muted">如不修改密码，请留空</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">确认密码</label>
                                <input type="password" class="form-control" @bind="confirmPassword" 
                                       placeholder="不修改请留空" />
                            </div>

                            <div class="mb-3">
                                <label class="form-label">后台管理路由</label>
                                <div class="input-group">
                                    <span class="input-group-text">/</span>
                                    <input type="text" class="form-control" @bind="settings.AdminRoute" 
                                           placeholder="admin" />
                                    <button class="btn btn-outline-secondary" type="button" @onclick="UpdateAdminRoute">
                                        <i class="bi bi-save"></i> 更新
                                    </button>
                                </div>
                                <small class="text-muted">修改后，需要使用新路径访问后台，当前后台路径: /@settings.AdminRoute</small>
                            </div>
                            
                            @if (!string.IsNullOrEmpty(routeUpdateMessage))
                            {
                                <div class="alert @(routeUpdateSuccess ? "alert-success" : "alert-danger") mt-3">
                                    <i class="bi @(routeUpdateSuccess ? "bi-check-circle" : "bi-exclamation-triangle")"></i>
                                    @routeUpdateMessage
                                </div>
                            }
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="text-end mt-3">
                <button class="btn btn-primary" @onclick="SaveSettings">
                    <i class="bi bi-save me-1"></i>保存设置
                </button>
            </div>
        }
    </div>
</div>

@code {
    /// <summary>
    /// 网站设置对象
    /// </summary>
    private SiteSettings settings = new SiteSettings();

    /// <summary>
    /// 是否正在加载设置
    /// </summary>
    private bool isLoadingSettings = true;

    /// <summary>
    /// 管理员用户名
    /// </summary>
    private string adminUsername = "";

    /// <summary>
    /// 管理员密码
    /// </summary>
    private string adminPassword = "";

    /// <summary>
    /// 确认密码
    /// </summary>
    private string confirmPassword = "";

    /// <summary>
    /// 路由更新消息
    /// </summary>
    private string routeUpdateMessage = "";

    /// <summary>
    /// 路由更新是否成功
    /// </summary>
    private bool routeUpdateSuccess = false;

    /// <summary>
    /// 组件初始化时加载数据
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await LoadSettingsAsync();
        await LoadAdminUserAsync();
    }

    /// <summary>
    /// 加载网站设置
    /// </summary>
    private async Task LoadSettingsAsync()
    {
        isLoadingSettings = true;
        try
        {
            settings = await SiteSettingsService.GetSiteSettingsAsync();
        }
        catch (Exception)
        {
            // 处理异常，使用默认值
            settings = new SiteSettings
            {
                SiteTitle = "导航网站",
                ThemeColor = "#3498db",
                AiModelName = "qwen3-235b-a22b"
            };
        }
        finally
        {
            isLoadingSettings = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 加载管理员用户信息
    /// </summary>
    private async Task LoadAdminUserAsync()
    {
        try
        {
            var adminUser = await UserService.GetAdminUserAsync();
            if (adminUser != null)
            {
                adminUsername = adminUser.Username;
            }
        }
        catch (Exception)
        {
            // 忽略异常
        }
    }

    /// <summary>
    /// 保存设置
    /// </summary>
    private async Task SaveSettings()
    {
        try
        {
            // 保存网站设置
            await SiteSettingsService.SaveSiteSettingsAsync(settings);

            // 如果管理员密码不为空，则更新管理员信息
            if (!string.IsNullOrEmpty(adminPassword))
            {
                if (adminPassword != confirmPassword)
                {
                    await JSRuntime.InvokeVoidAsync("alert", "两次密码输入不一致，请重新输入");
                    return;
                }

                await UserService.UpdateAdminUserAsync(adminUsername, adminPassword);
            }

            await JSRuntime.InvokeVoidAsync("alert", "设置保存成功");
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"保存失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 更新管理路由
    /// </summary>
    private async Task UpdateAdminRoute()
    {
        if (string.IsNullOrWhiteSpace(settings.AdminRoute))
        {
            routeUpdateMessage = "管理路由不能为空";
            routeUpdateSuccess = false;
            return;
        }

        if (settings.AdminRoute.Contains(" ") || settings.AdminRoute.Contains("/"))
        {
            routeUpdateMessage = "管理路由不能包含空格或斜杠";
            routeUpdateSuccess = false;
            return;
        }

        try
        {
            var oldRoute = await SiteSettingsService.GetAdminRouteAsync();
            var result = await SiteSettingsService.UpdateAdminRouteAsync(settings.AdminRoute);
            
            if (result)
            {
                routeUpdateMessage = $"管理路由已更新为 /{settings.AdminRoute}，请记住新的访问地址";
                routeUpdateSuccess = true;
            }
            else
            {
                routeUpdateMessage = "管理路由更新失败";
                routeUpdateSuccess = false;
            }
        }
        catch (Exception ex)
        {
            routeUpdateMessage = $"更新管理路由时发生错误: {ex.Message}";
            routeUpdateSuccess = false;
        }
    }
} 